// 玩家类
class Player {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.size = GAME_CONFIG.PLAYER_SIZE;
        this.speed = GAME_CONFIG.PLAYER_SPEED;
        this.maxHealth = 100;
        this.health = this.maxHealth;
        this.level = 1;
        this.experience = 0;
        this.experienceToNextLevel = getCumulativeExperienceForLevel(2); // 第2级所需累积经验
        
        // 移动控制
        this.keys = {
            up: false,
            down: false,
            left: false,
            right: false
        };
        
        // 动画相关
        this.animationFrame = 0;
        this.animationSpeed = 0.2;
        this.direction = { x: 0, y: 0 };
        
        // 无敌时间（被击中后短暂无敌）
        this.invulnerable = false;
        this.invulnerableTime = 0;
        this.invulnerableDuration = 1000; // 1秒
        
        // 生命恢复
        this.healthRegen = false;
        this.healthRegenRate = 0;
        this.healthRegenTimer = 0;
        
        this.setupControls();
    }
    
    // 设置键盘控制
    setupControls() {
        document.addEventListener('keydown', (e) => {
            switch(e.key.toLowerCase()) {
                case 'w':
                case 'arrowup':
                    this.keys.up = true;
                    break;
                case 's':
                case 'arrowdown':
                    this.keys.down = true;
                    break;
                case 'a':
                case 'arrowleft':
                    this.keys.left = true;
                    break;
                case 'd':
                case 'arrowright':
                    this.keys.right = true;
                    break;
            }
        });
        
        document.addEventListener('keyup', (e) => {
            switch(e.key.toLowerCase()) {
                case 'w':
                case 'arrowup':
                    this.keys.up = false;
                    break;
                case 's':
                case 'arrowdown':
                    this.keys.down = false;
                    break;
                case 'a':
                case 'arrowleft':
                    this.keys.left = false;
                    break;
                case 'd':
                case 'arrowright':
                    this.keys.right = false;
                    break;
            }
        });
    }
    
    // 更新玩家状态
    update(deltaTime) {
        this.updateMovement(deltaTime);
        this.updateAnimation(deltaTime);
        this.updateInvulnerability(deltaTime);
        this.updateHealthRegen(deltaTime);
    }
    
    // 更新移动
    updateMovement(deltaTime) {
        let dx = 0;
        let dy = 0;
        
        // 使用deltaTime确保帧率无关的移动
        const moveDistance = this.speed * (deltaTime / 16.67); // 以60FPS为基准
        
        if (this.keys.up) dy -= moveDistance;
        if (this.keys.down) dy += moveDistance;
        if (this.keys.left) dx -= moveDistance;
        if (this.keys.right) dx += moveDistance;
        
        // 对角线移动时保持相同速度
        if (dx !== 0 && dy !== 0) {
            dx *= 0.707; // 1/√2
            dy *= 0.707;
        }
        
        // 更新位置
        this.x += dx;
        this.y += dy;
        
        // 边界检查（限制在世界范围内）
        this.x = Utils.clamp(this.x, this.size, GAME_CONFIG.WORLD_WIDTH - this.size);
        this.y = Utils.clamp(this.y, this.size, GAME_CONFIG.WORLD_HEIGHT - this.size);
        
        // 更新方向（用于动画）
        if (dx !== 0 || dy !== 0) {
            this.direction.x = dx;
            this.direction.y = dy;
        }
    }
    
    // 更新动画
    updateAnimation(deltaTime) {
        if (this.direction.x !== 0 || this.direction.y !== 0) {
            this.animationFrame += this.animationSpeed * deltaTime;
            if (this.animationFrame >= 4) {
                this.animationFrame = 0;
            }
        }
    }
    
    // 更新无敌状态
    updateInvulnerability(deltaTime) {
        if (this.invulnerable) {
            this.invulnerableTime += deltaTime;
            if (this.invulnerableTime >= this.invulnerableDuration) {
                this.invulnerable = false;
                this.invulnerableTime = 0;
            }
        }
    }
    
    // 更新生命恢复
    updateHealthRegen(deltaTime) {
        if (this.healthRegen && this.health < this.maxHealth) {
            this.healthRegenTimer += deltaTime;
            if (this.healthRegenTimer >= 1000) { // 每秒恢复一次
                this.heal(this.healthRegenRate);
                this.healthRegenTimer = 0;
            }
        }
    }
    
    // 渲染玩家
    render(ctx) {
        ctx.save();
        
        // 无敌状态闪烁效果
        if (this.invulnerable) {
            const alpha = Math.sin(this.invulnerableTime * 0.01) * 0.5 + 0.5;
            ctx.globalAlpha = alpha;
        }
        
        // 使用精灵渲染玩家
        const playerSprite = window.spriteManager ? window.spriteManager.getSprite('player') : null;
        if (playerSprite) {
            playerSprite.render(ctx, this.x, this.y, this.size * 2, this.size * 2);
        } else {
            // 备用渲染（圆形）
            ctx.fillStyle = '#4a90e2';
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
            ctx.fill();
            
            ctx.strokeStyle = '#ffffff';
            ctx.lineWidth = 2;
            ctx.stroke();
        }
        
        // 绘制方向指示器
        if (this.direction.x !== 0 || this.direction.y !== 0) {
            const angle = Math.atan2(this.direction.y, this.direction.x);
            const indicatorLength = this.size + 5;
            const endX = this.x + Math.cos(angle) * indicatorLength;
            const endY = this.y + Math.sin(angle) * indicatorLength;
            
            ctx.strokeStyle = '#ffffff';
            ctx.lineWidth = 3;
            ctx.beginPath();
            ctx.moveTo(this.x, this.y);
            ctx.lineTo(endX, endY);
            ctx.stroke();
        }
        
        // 绘制等级指示器
        ctx.fillStyle = '#ffd700';
        ctx.font = '12px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(this.level.toString(), this.x, this.y - this.size - 5);
        
        ctx.restore();
    }
    
    // 受到伤害
    takeDamage(damage) {
        if (this.invulnerable) return false;
        
        this.health -= damage;
        this.health = Math.max(0, this.health);
        
        // 激活无敌状态
        this.invulnerable = true;
        this.invulnerableTime = 0;
        
        return this.health <= 0;
    }
    
    // 恢复生命值
    heal(amount) {
        this.health = Math.min(this.maxHealth, this.health + amount);
    }
    
    // 获得经验
    gainExperience(amount) {
        this.experience += amount;
        
        // 播放经验获得音效
        if (window.game && window.game.sounds && window.game.sounds.experience) {
            window.game.soundGenerator.playSound(window.game.sounds.experience);
        }
        
        // 检查是否升级 - 使用累积经验值比较
        let nextLevelCumulative = getCumulativeExperienceForLevel(this.level + 1);
        while (this.experience >= nextLevelCumulative) {
            this.levelUp();
            nextLevelCumulative = getCumulativeExperienceForLevel(this.level + 1);
        }
    }
    
    // 升级
    levelUp() {
        this.level++;
        // 更新下一级所需的累积经验
        this.experienceToNextLevel = getCumulativeExperienceForLevel(this.level + 1);
        
        // 升级时恢复一些生命值
        this.heal(20);
        
        // 触发升级事件
        if (window.game && window.game.onPlayerLevelUp) {
            window.game.onPlayerLevelUp(this);
        }
    }
    
    // 获取经验进度百分比
    getExperienceProgress() {
        const currentLevelCumulative = getCumulativeExperienceForLevel(this.level);
        const nextLevelCumulative = getCumulativeExperienceForLevel(this.level + 1);
        const currentProgress = this.experience - currentLevelCumulative;
        const totalRequired = nextLevelCumulative - currentLevelCumulative;
        return totalRequired > 0 ? currentProgress / totalRequired : 0;
    }
    
    // 获取生命值百分比
    getHealthPercentage() {
        return this.health / this.maxHealth;
    }
    
    // 检查是否死亡
    isDead() {
        return this.health <= 0;
    }
    
    // 添加护盾
    addShield(duration) {
        // 护盾功能可以在这里实现
        console.log(`护盾激活，持续${duration}ms`);
    }
    
    // 添加速度提升
    addSpeedBoost(multiplier, duration) {
        const originalSpeed = this.speed;
        this.speed *= multiplier;
        
        setTimeout(() => {
            this.speed = originalSpeed;
        }, duration);
    }
    
    // 重置玩家状态
    reset() {
        this.health = this.maxHealth;
        this.level = 1;
        this.experience = 0;
        this.experienceToNextLevel = getCumulativeExperienceForLevel(2); // 第2级所需累积经验
        this.invulnerable = false;
        this.invulnerableTime = 0;
        this.x = GAME_CONFIG.CANVAS_WIDTH / 2;
        this.y = GAME_CONFIG.CANVAS_HEIGHT / 2;
    }
    
    // 获取碰撞边界
    getBounds() {
        return {
            x: this.x - this.size,
            y: this.y - this.size,
            width: this.size * 2,
            height: this.size * 2
        };
    }
    
    // 检查与其他对象的碰撞
    collidesWith(other) {
        return Utils.circleCollision(
            this.x, this.y, this.size,
            other.x, other.y, other.size || other.radius || 0
        );
    }
    
    // 获取当前等级所需的累积经验值
    getExperienceForCurrentLevel() {
        // 确保 level 至少为 1
        const level = Math.max(1, this.level);
        return getCumulativeExperienceForLevel(level);
    }

    // 获取下一等级所需的累积经验值
    getExperienceForNextLevel() {
        // 确保 level 至少为 1，并且计算 nextLevel 的经验值
        const nextLevel = Math.max(1, this.level + 1);
        return getCumulativeExperienceForLevel(nextLevel); // 确保这里正确返回经验值，避免 undefined
    }

    // 获取达到下一等级还需要的经验值
    getExperienceToNextLevel() {
        const currentLevelExp = this.getExperienceForCurrentLevel();
        const nextLevelExp = this.getExperienceForNextLevel();
        return nextLevelExp - currentLevelExp;
    }

    // 获取经验条的显示值
    getExperienceDisplayValues() {
        const currentExp = this.experience; // 当前经验值
        let expToNextLevel = this.getExperienceToNextLevel(); // 达到下一等级还需要的经验值

        // 确保 expToNextLevel 不为 undefined
        if (expToNextLevel === undefined) {
            console.error('Experience to next level is undefined');
            expToNextLevel = 0; // 提供合理的默认值
        }

        return { current: currentExp, total: expToNextLevel };
    }
} 